<template>
  <el-container class="create-subtask-container">
    <el-header class="header">
      <h2 style="font-weight: bold;">创建子任务</h2>
    </el-header>
    <el-main>
      <el-card class="form-card">
        <el-form :model="subtaskForm" label-width="120px">
          <el-form-item label="子任务描述">
            <el-input v-model="subtaskForm.description" placeholder="请输入描述"></el-input>
          </el-form-item>
          <el-form-item label="开始日期">
            <el-date-picker
              v-model="subtaskForm.start_date"
              type="date"
              placeholder="选择开始日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker
              v-model="subtaskForm.end_date"
              type="date"
              placeholder="选择结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="分配给">
            <el-select v-model="subtaskForm.assigned_to" placeholder="选择分配给的成员">
              <el-option
                v-for="user in users"
                :key="user.user_id"
                :label="user.username"
                :value="user.user_id"
              />
            </el-select>
          </el-form-item>
          <!-- 显示小组ID（不可编辑） -->
          <el-form-item label="小组ID">
            <el-input v-model="subtaskForm.group_id" disabled></el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="createSubtask">确认创建</el-button>
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script>
import { defineComponent, ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import axios from "@/axiosInstance";

export default defineComponent({
  name: "CreateSubtask",
  setup() {
    const router = useRouter();
    const route = useRoute();
    // 从 URL 查询参数中获取 taskId, groupId, sysUserId
    const taskId = ref(route.query.taskId);
    const groupId = ref(route.query.groupId);
    const sysUserId = ref(route.query.sysUserId);
    const createSubtaskDialogVisible = ref(false);

    // 用于创建子任务的表单数据
    const subtaskForm = ref({
      description: "",
      start_date: "",
      end_date: "",
      assigned_to: null,
      group_id: groupId.value,  // 默认赋值为 URL 中传入的 groupId
      task: taskId.value       // 如果需要关联任务，也传入 taskId
    });

    // 获取可选的用户列表（用于下拉框选择）
    const users = ref([]);
    const fetchUsers = async () => {
      try {
        const response = await axios.get("http://39.105.217.183:8000/api/all-users/");
        users.value = response.data;
      } catch (error) {
        console.error("Error fetching users:", error.message || error);
      }
    };

    onMounted(() => {
      console.log("CreateSubtask 页面参数：", taskId.value, groupId.value, sysUserId.value);
      fetchUsers();
    });

    // 创建子任务请求
    const createSubtask = async () => {
      try {
        // 将日期对象转换为 ISO 格式的日期字符串（只保留日期部分）
    const formattedStartDate = subtaskForm.value.start_date instanceof Date
      ? subtaskForm.value.start_date.toISOString().split("T")[0]
      : subtaskForm.value.start_date;
    const formattedEndDate = subtaskForm.value.end_date instanceof Date
      ? subtaskForm.value.end_date.toISOString().split("T")[0]
      : subtaskForm.value.end_date;

    const payload = {
      user_id: sysUserId.value,
      description: subtaskForm.value.description,
      start_date: formattedStartDate,
      end_date: formattedEndDate,
      assigned_to: Number(subtaskForm.value.assigned_to),
      group_id: Number(groupId.value),
      task: Number(taskId.value)
    };

        console.log("创建子任务 payload:", payload);
        const response = await axios.post("http://39.105.217.183:8000/api/subtasks/", payload);
        console.log("Subtask created:", response.data);
        // 创建成功后，可以跳转回原页面或提示成功信息
        createSubtaskDialogVisible.value = false;
        await router.push({
          path: '/task-calendar',
          query: { taskId: taskId.value, sysUserId: sysUserId.value, groupId: groupId.value }
        });
      } catch (error) {
        console.error("Error creating subtask:", error.message || error);
      }
    };

    const goBack = () => {
      router.back();
    };

    return {
      subtaskForm,
      users,
      createSubtask,
      goBack,
    };
  }
});
</script>

<style scoped>
.create-subtask-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
  background-color: #f5f7fa;
}

.header {
  text-align: center;
  margin-bottom: 20px;
}

.form-card {
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
</style>